package by.grsu.shakh.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import by.grsu.shakh.entity.Book;
import by.grsu.shakh.table.BookTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

public class BookDao extends AbstractDao<BookTable, Book> {

	public BookDao(String rootFolderPath) {
		super(rootFolderPath);
	}

	public List<Book> searchByName(String name) {
		final BookTable bookTable = deserializeFromXml();
		List<Book> listBook = new ArrayList<Book>();
		for (Book b : bookTable.getRows()) {
			if (b.getName().equals(name)) {
				listBook.add(b);
			}
		}
		return listBook;
	}

	public List<Book> searchByAuthor(String s) {
		final BookTable bookTable = deserializeFromXml();
		List<Book> result = new ArrayList<Book>();
		for (Book b : bookTable.getRows()) {
			if (b.getAuthor().equals(s)) {
				result.add(b);
			}
		}
		return result;
	}

	public List<Book> searchByDate(Date d) {
		final BookTable bookTable = deserializeFromXml();
		List<Book> listBook = new ArrayList<Book>();
		for (Book b : bookTable.getRows()) {
			if (b.getDate().equals(d)) {
				listBook.add(b);
			}
		}
		return listBook;
	}

	public void saveNew(Book newBook) {
		newBook.setId(getNextId());
		final BookTable bookTable = deserializeFromXml();
		bookTable.getRows().add(newBook);
		serializeToXml(bookTable);

	}

	@Override
	public void update(Book entity) {
		final BookTable bookTable = deserializeFromXml();
		for (Book b : bookTable.getRows()) {
			if (b.getId().equals(entity.getId())) {
				b.setAuthor(entity.getAuthor());
				b.setCatalogId(entity.getCatalogId());
				b.setDate(entity.getDate());
				b.setDescription(entity.getDescription());
				b.setName(entity.getName());
				b.setPublishing(entity.getPublishing());
			}
		}
		serializeToXml(bookTable);
	}

	@Override
	public Book get(Serializable id) {
		final BookTable bookTable = deserializeFromXml();
		for (Book b : bookTable.getRows()) {
			if (b.getId().equals(id)) {
				return b;
			}
		}
		return null;
	}

	@Override
	public List<Book> getAll() {
		BookTable bookTable = deserializeFromXml();
		return bookTable.getRows();
	}

	@Override
	public void delete(Serializable id) {
		final BookTable bookTable = deserializeFromXml();
		Book toBeDeletedBook = null;
		for (Book b : bookTable.getRows()) {
			if (b.getId().equals(id)) {
				toBeDeletedBook = b;
			}
		}
		bookTable.getRows().remove(toBeDeletedBook);
		serializeToXml(bookTable);
	}

	@Override
	protected Class<BookTable> getTableClass() {
		return BookTable.class;
	}

}
